package com.glodon.utils.util;

import com.alibaba.fastjson.JSONArray;
import net.sf.json.JSONObject;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import javax.imageio.ImageIO;
import javax.net.ssl.SSLException;

/**
 * Created by Administrator on 2017-8-2.
 */
public class ImageToTextUtil {

    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();

    public static List tesseractText_face(String filePath) {
        byte[] buff = new byte[0];
        ImgCompress imgCom = null;
        try {
            imgCom = new ImgCompress(filePath);
            buff = imgCom.resizeFix(800, 800);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

        String url = "https://api-cn.faceplusplus.com/imagepp/v1/recognizetext";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, byte[]> byteMap = new HashMap<>();
        map.put("api_key", "WoII964FmyOlZwTrZOj9yDeSE9CwH6bU");
        map.put("api_secret", "CD2N5SIfa0y6UAxmV4G3P47ECHh6cdyL");
        byteMap.put("image_file", buff);
        List<JSONArray> analyList = new ArrayList<>();

        List<String> list = new ArrayList<>();
        try{
            byte[] bacd = post(url, map, byteMap);
            String str = new String(bacd);

            Map resultMap = (Map) JSONArray.parseObject(str, Map.class);

            List<JSONArray> result = (List<JSONArray>) resultMap.get("result");

            for (int i = 0 ; i< result.size(); i++ ) {

                JSONObject json  = JSONObject.fromObject(result.get(i));

                list.add((String) json.get("value"));
                analyList.addAll((List<JSONArray>) json.get("child-objects"));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return analyList;
    }

    public static List anaylizeList(List<JSONArray> list) {

        for (JSONArray objects : list) {

        }

        return null;
    }

    public static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while(iter.hasNext()){
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if(fileMap != null && fileMap.size() > 0){
            Iterator fileIter = fileMap.entrySet().iterator();
            while(fileIter.hasNext()){
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try{
            if(code == 200){
                ins = conne.getInputStream();
            }else{
                ins = conne.getErrorStream();
            }
        }catch (SSLException e){
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while((len = ins.read(buff)) != -1){
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }
    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }
    private static String encode(String value) throws Exception{
        return URLEncoder.encode(value, "UTF-8");
    }

    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String tesseract(InputStream fileInputStream) {
        String result = "";
        try {
            BufferedImage bi = ImageIO.read(fileInputStream);
            ITesseract instance = new Tesseract();  // JNA Interface Mapping
            instance.setLanguage("chi_sim");
//            instance.setLanguage("num");
            //这句非常重要
            instance.setDatapath("D:\\Tesseract-OCR\\tessdata");
            result = instance.doOCR(bi);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (TesseractException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
